<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('1000px')"
    :visible="visible"
    :title="title"
    @open="open"
    @close="close"
  >
    <template v-if="step === 1">
      <el-form
        ref="firstForm"
        :model="nodeData"
        label-width="auto"
        :rules="rules"
        class="flex flex-wrap pr-30"
      >
        <el-form-item :label="$t('BELONGS_REGION_STATION_NAME')" prop="stationId" class="w-50">
          <el-input v-model="nodeData.stationId" class="hide" />
          <!-- 区域选择 -->
          <region-cascader
            class="block"
            :selected-ids="[nodeData.stationId]"
            :clearable="false"
            data-name="stationTree"
            placeholder="REGION_STATION"
            :disabled="
              type === 'mod' &&
                ((oldStationId === nodeData.stationId &&
                  (stationData.status === 'CONSIGN' || stationData.status === 'REPAIR')) ||
                  segmentList.length > 0)
            "
            @change="regionChange"
          />
        </el-form-item>
        <el-form-item :label="$t('STATION_CODE')" class="w-50">
          <el-input :value="nodeData.stationId" readonly />
        </el-form-item>
        <el-form-item :label="$t('BELONGS_ROOM_NAME')" class="w-50">
          <el-select
            v-model="nodeData.roomId"
            :disabled="type === 'mod' && segmentList.length > 0 && nodeData.roomId !== ''"
            clearable
            placeholder=""
          >
            <el-option
              v-for="item in roomList"
              :key="item.regionId"
              :value="item.regionId"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('NODE_TYPE')" prop="nodeType" class="w-50">
          <el-select
            v-model="nodeData.nodeType"
            placeholder=""
            :disabled="type !== 'add'"
          >
            <el-option
              v-for="item in allNodeTypesList"
              :key="item.id"
              :value="item.code"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('NODE_NAME')" prop="nodeName" class="w-50">
          <el-select
            v-if="nodeData.nodeCategory === 'AFS' && type === 'add'"
            v-model="afsId"
            placeholder=""
            filterable
            @change="nodeNameChanged"
          >
            <el-option
              v-for="item in deviceList"
              :key="item.deviceId"
              :value="item.deviceId"
              :label="item.deviceName"
            />
          </el-select>
          <template v-else>
            <!-- <el-tooltip :content="$t('CHARACTERS_SUGGEST', {msg: '~%&[]{}()=_+'})" placement="top" effect="light"> -->
            <el-input v-model.trim="nodeData.nodeName" maxlength="50" />
            <!-- </el-tooltip> -->
          </template>
        </el-form-item>
        <el-form-item :label="$t('NODE_MODEL')" class="w-50">
          <el-input
            v-model="nodeData.model"
            maxlength="32"
            :readonly="nodeData.nodeType === 'AFS' || nodeData.nodeType === 'AOCC'"
          />
        </el-form-item>
        <el-form-item :label="$t('RESOURCE_CODE')" class="w-50">
          <el-input v-model="nodeData.resourceCode" maxlength="32" />
        </el-form-item>
        <el-form-item :label="$t('VENDOR')" class="w-50">
          <el-input v-model="nodeData.company" maxlength="32" />
        </el-form-item>
        <template v-if="nodeData.nodeType === 'SPLICE_CLOSURE'">
          <el-form-item
            :label="$t('JOINT_SPECIFICATIONS')"
            class="w-50"
            prop="properties.spliceClosure.number"
          >
            <el-select v-model="nodeData.properties.spliceClosure.number" placeholder="">
              <el-option
                v-for="item in jointNorms"
                :key="item.value"
                :value="item.value"
                :label="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('APPLICATION')"
            class="w-50"
            prop="properties.spliceClosure.useOccasionType"
          >
            <el-select
              v-model="nodeData.properties.spliceClosure.useOccasionType"
              placeholder=""
            >
              <el-option
                v-for="item in useOccation"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('CONNECTION_METHOD')"
            class="w-50"
            prop="properties.spliceClosure.connectionModeType"
          >
            <el-select
              v-model="nodeData.properties.spliceClosure.connectionModeType"
              placeholder=""
              @change="changeConMethod"
            >
              <el-option
                v-for="item in conMethod"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
    </template>
    <template v-else>
      <light-split
        v-if="nodeData.nodeCategory === 'LIGHT_SPLIT'"
        ref="LIGHT_SPLIT"
        :device-prop="nodeData.properties"
      />
      <flange
        v-if="nodeData.nodeCategory === 'ODF'"
        ref="ODF"
        :device-prop="nodeData.properties"
        :type="type"
      />
      <Transmission
        v-if="nodeData.nodeCategory === 'TRANSPORT'"
        ref="TRANSPORT"
        :device-prop="nodeData.properties"
        :row-data="rowData"
        :type="type"
      />
      <!--连接方式 分歧 下一步-->
      <Divergence
        v-if="
          nodeData.nodeCategory === 'SPLICE_CLOSURE' &&
            nodeData.properties.spliceClosure &&
            nodeData.properties.spliceClosure.connectionModeType === 'DIVERGENCE'
        "
        ref="SPLICE_CLOSURE"
        :device-prop="nodeData.properties"
        :row-data="rowData"
        :type="type"
      />
    </template>
    <template v-slot:footer>
      <el-button @click="close">{{ $t("CANCEL") }}</el-button>
      <template
        v-if="
          nodeData.nodeCategory !== 'AFS' &&
            nodeData.properties.spliceClosure &&
            nodeData.properties.spliceClosure.connectionModeType !== 'DIRECT_CONNECTION'
        "
      >
        <el-button v-if="step == 1" @click="next">{{ $t("NEXT") }}</el-button>
        <el-button v-else @click="prev">{{ $t("PREVIOUS") }}</el-button>
      </template>
      <el-button
        v-if="
          step == 2 ||
            nodeData.nodeCategory === 'AFS' ||
            (nodeData.properties.spliceClosure &&
              nodeData.properties.spliceClosure.connectionModeType === 'DIRECT_CONNECTION')
        "
        type="primary"
        @click="$debounce(save)"
      >{{ $t("SAVE") }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { generateUuid, deepClone } from '@/utils/common'
  import nodeApi from '@/api/oen/NodeApi'
  import cableApi from '@/api/oen/CableApi'
  import NetworkSegmentApi from '@/api/oen/NetworkSegmentApi'
  import RegionCascader from '@/components/RegionCascader'
  import LightSplit from './components/second/LightSplit'
  import Flange from './components/second/Flange'
  import Transmission from './components/second/Transmission'
  import Divergence from './components/second/DivergencePort.vue'
  export default {
    components: { RegionCascader, LightSplit, Flange, Transmission, Divergence },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: ''
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      const defaultInputUuid = generateUuid()
      const defaultOutputUuid = generateUuid()
      return {
        step: 1,
        roomList: [],
        nodeData: {
          nodeCategory: '',
          nodeType: '',
          nodeName: '',
          nodeId: '',
          stationId: '',
          roomId: '',
          resourceCode: '',
          company: '',
          model: '',
          properties: {
            odf: {
              faceNum: 1,
              flangeType: 'LC',
              faceList: [
                {
                  capacity: 12,
                  connNum: 0,
                  faceName: 'P1',
                  idleNum: 0,
                  installNum: 12
                }
              ]
            },
            //
            split: {
              inNum: 1,
              outNum: ''
            },
            trans: {
              shelfNum: 1,
              shelfList: []
            },
            spliceClosure: {
              // 接头盒默认信息
              number: '',
              useOccasionType: '',
              connectionModeType: '',
              cableId: '',
              virtualFlag: false,
              inputList: [
                {
                  spliceId: defaultInputUuid,
                  spliceName: '进口1',
                  number: '12'
                }
              ],
              outputList: [
                {
                  spliceId: defaultOutputUuid,
                  spliceName: '出口1',
                  number: '12'
                }
              ],
              splicePortInfoList: [
                {
                  inputSpliceId: '',
                  inputSplicePortName: '',
                  outputSpliceId: '',
                  outputSplicePortName: ''
                }
              ]
            }
          }
        },
        stationData: {},
        oldStationId: '',
        deviceList: [],
        afsId: '',
        segmentList: [],
        curNodeType: false, // 判断选的站点类型
        cableList: [], // 光缆列表
        isprev: false // 判断是否点击上一步
      }
    },
    computed: {
      ...mapGetters(['baseRegionList', 'allNodeTypes', 'dictList']),
      allNodeTypesList() {
        if (this.curNodeType) {
          return this.allNodeTypes.filter((i) => i.code === 'SPLICE_CLOSURE')
        }
        return this.allNodeTypes.filter((i) => i.code !== 'SPLICE_CLOSURE')
      },
      jointNorms() {
        return this.dictList.JOINT_NORMS
      },
      useOccation() {
        return this.dictList.APPLICATION
      },
      conMethod() {
        return this.dictList.CONNECTION_METHOD
      },
      title() {
        const titleName = {
          view: this.$t('VIEW_NODE'),
          add: this.$t('ADDE_NODE'),
          mod: this.$t('EDIT_NODE')
        }
        return titleName[this.type]
      },
      rules() {
        return {
          stationId: [
            {
              required: true,
              message: this.$t('SELECT_STATION'),
              trigger: 'blur'
            }
          ],
          nodeType: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('NODE_TYPE'),
              trigger: 'change'
            }
          ],
          nodeName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('NODE_NAME'),
              trigger: 'blur'
            }
          ],
          'properties.spliceClosure.number': [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(
                    new Error(this.$t('PLEASE_SELECT') + this.$t('JOINT_SPECIFICATIONS'))
                  )
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ],
          'properties.spliceClosure.useOccasionType': [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(new Error(this.$t('PLEASE_SELECT') + this.$t('APPLICATION')))
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ],
          'properties.spliceClosure.connectionModeType': [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(
                    new Error(this.$t('PLEASE_SELECT') + this.$t('CONNECTION_METHOD'))
                  )
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ],
          'properties.spliceClosure.cableId': [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(new Error(this.$t('PLEASE_SELECT') + this.$t('BINDING_CABLES')))
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ]
        }
      }
    },
    watch: {
      'nodeData.nodeType': function(val) {
        const nodeTypeData = this.allNodeTypes.find((i) => i.code === val)
        this.nodeData.nodeCategory = nodeTypeData ? nodeTypeData.nodeCategory : ''
        if (this.type === 'add') {
          this.nodeData.nodeId = ''
        }
        if (this.nodeData.nodeCategory === 'AFS' && this.type === 'add') {
          this.nodeData.model = ''
          this.getNotExistsNodeList()
        }
      }
    },
    methods: {
      changeConMethod(val) {
        // 连接方式改变
        if (val === 'DIRECT_CONNECTION') {
          this.getCableList()
        }
      },
      getCableList() {
        // 获取光缆列表
        const queryData = {
          page: { page: 1, size: 1000 }
        }
        cableApi.queryPage(queryData).then((res) => {
          this.cableList = res.list || []
        })
      },
      getLinkNode() {
        this.segmentList = []
        NetworkSegmentApi.linkNode({
          nodeId: this.rowData.nodeId
        }).then((res) => {
          this.segmentList = res || []
        })
      },
      nodeNameChanged() {
        const afsNode = this.deviceList.find((i) => i.deviceId === this.afsId)
        this.nodeData.nodeId = this.afsId
        this.nodeData.nodeName = afsNode.deviceName
        this.nodeData.model = afsNode.model
        this.nodeData.company = afsNode.company
        console.log('this.nodeData', this.nodeData)
      },
      // 从AFS获取某节点类型不存在的节点
      getNotExistsNodeList() {
        this.nodeData.nodeName = ''
        this.afsId = ''
        this.deviceList = []
        nodeApi
          .getNotExistsNodeList({
            afsType: this.nodeData.nodeType
          })
          .then((res) => {
            this.deviceList = res || []
          })
      },
      open() {
        this.step = 1
        this.$nextTick(() => {
          this.$refs.firstForm && this.$refs.firstForm.clearValidate()
          this.nodeData.roomId = this.rowData.roomId
        })
        const newData = this.$options.data().nodeData
        const rowData = deepClone(this.rowData)
        this.nodeData = this.rowData.id ? { ...newData, ...rowData } : newData
        // 修改情况下，节点所属站点已删除，置空站点id
        if (
          this.type !== 'add' &&
          !this.baseRegionList.some((i) => i.regionId === this.nodeData.stationId)
        ) {
          this.nodeData.stationId = ''
        }
        this.oldStationId = this.nodeData.stationId
        this.segmentList = []
      // if (this.type === 'mod' && this.oldStationId !== '') {
      //   this.getLinkNode()
      // }
      },
      // 下一步
      next() {
        this.$refs.firstForm.validate((valid) => {
          if (valid) {
            this.step = 2
          }
        })
      },
      prev() {
        // 上一步
        this.step = 1
        this.isprev = true
      },
      // 保存
      save() {
        if (document.getElementsByClassName('el-message--error').length) return
        if (this.nodeData.nodeCategory === 'LIGHT_SPLIT') {
          delete this.nodeData.properties.odf
          delete this.nodeData.properties.trans
          delete this.nodeData.properties.spliceClosure
        }
        if (this.nodeData.nodeCategory === 'ODF') {
          delete this.nodeData.properties.split
          delete this.nodeData.properties.trans
          delete this.nodeData.properties.spliceClosure
          const faceList = this.nodeData.properties.odf.faceList
          if (faceList.some((i) => i.faceName === '')) {
            this.$message.error(this.$t('ENTER_FACE_NAME'))
            return
          }
        }
        if (this.nodeData.nodeCategory === 'TRANSPORT') {
          const shelfList = this.nodeData.properties.trans.shelfList
          if (shelfList.some((i) => i.slotList.some((j) => j.slotName === ''))) {
            this.$message.error(this.$t('ENTER_SLOT_NAME'))
            return
          }
          delete this.nodeData.properties.odf
          delete this.nodeData.properties.split
          delete this.nodeData.properties.spliceClosure
        }
        if (this.nodeData.nodeCategory === 'SPLICE_CLOSURE') {
          delete this.nodeData.properties.odf
          delete this.nodeData.properties.trans
          delete this.nodeData.properties.split
          if (
            this.nodeData.properties.spliceClosure.connectionModeType ===
            'DIRECT_CONNECTION'
          ) {
            this.nodeData.properties.spliceClosure.splicePortInfoList = []
            this.nodeData.properties.spliceClosure.inputList = []
            this.nodeData.properties.spliceClosure.outputList = []
            this.nodeData.properties.spliceClosure.virtualFlag = true
          } else {
            let list = this.$refs[this.nodeData.nodeCategory].getSplicePortInfoList()
            list = list.map((item, index) => {
              return {
                ...item,
                sort: index
              }
            })
            this.nodeData.properties.spliceClosure.splicePortInfoList = list
          }
        }
        if (this.nodeData.nodeCategory === 'AFS') {
          delete this.nodeData.properties.spliceClosure
        }
        // afs设备校验
        if (
          this.nodeData.nodeCategory === 'AFS' ||
          this.nodeData.properties.spliceClosure.connectionModeType === 'DIRECT_CONNECTION'
        ) {
          this.$refs.firstForm.validate((valid) => {
            if (!valid) return
            this.nodeData.id ? this.updateNode() : this.addNode()
          })
        } else {
          // 第二步校验
          this.secondSave()
        }
      },
      secondSave() {
        if (
          this.nodeData.nodeCategory === 'SPLICE_CLOSURE' &&
          this.nodeData.properties.spliceClosure.connectionModeType !== 'DIRECT_CONNECTION'
        ) {
          const {
            inputList,
            outputList,
            splicePortInfoList
          } = this.nodeData.properties.spliceClosure
          if (
            inputList.some((i) => !i.spliceName || !i.number) ||
            outputList.some((i) => !i.spliceName || !i.number) ||
            splicePortInfoList.some(
              (i) => !i.inputSplicePortName || !i.outputSplicePortName
            )
          ) {
            this.$message.error(this.$t('CONFIGURATION_INFORMATION'))
            return
          }
          // 修改端口配置
          if (this.nodeData.id) {
            const oldList = this.rowData.properties.spliceClosure.splicePortInfoList
            const newList = this.nodeData.properties.spliceClosure.splicePortInfoList
            // console.log('newList----', newList)
            this.delPortIds = [] // 删除id
            this.portList = [] // 修改数据
            this.finalList = [] // 未修改数据
            oldList.forEach((i, index) => {
              const obj = newList.find(
                (j) =>
                  j.inputSplicePortId === i.inputSplicePortId &&
                  j.inputSplicePortName === i.inputSplicePortName &&
                  j.outputSplicePortId === i.outputSplicePortId &&
                  j.outputSplicePortName === i.outputSplicePortName
              )
              if (obj) {
                this.finalList.push(i)
              } else {
                this.delPortIds.push(i.inputSplicePortId, i.outputSplicePortId)
                const editObj = newList.find(
                  (j) =>
                    j.inputSplicePortId === i.inputSplicePortId &&
                    j.outputSplicePortId === i.outputSplicePortId
                )
                if (editObj) {
                  this.portList.push({
                    inputSpliceId: editObj.inputSpliceId,
                    inputSplicePortName: editObj.inputSplicePortName,
                    outputSpliceId: editObj.outputSpliceId,
                    outputSplicePortName: editObj.outputSplicePortName,
                    sort: index
                  })
                }
              }
            })
            // 新增的端口列表
            const arr = newList.filter(
              (j) => !j.inputSplicePortId && !j.outputSplicePortId
            )
            this.portList = this.portList.concat(arr)
            this.updateSplicePortInfo()
            return
          }
          this.addNode()
          return
        }
        this.$refs[this.nodeData.nodeCategory].$refs.form.validate((valid) => {
          if (!valid) return
          this.nodeData.id ? this.updateNode() : this.addNode()
        })
      },
      updateSplicePortInfo() {
        if (!this.delPortIds.length && !this.portList.length) {
          this.$message.warning(this.$t('NO_CHANGED'))
          return
        }
        const params = {
          node: this.nodeData,
          delPortIds: this.delPortIds,
          portList: this.portList,
          finalList: this.finalList
        }
        console.log('params---------', params)
        nodeApi.updateSplicePortInfo(params).then((res) => {
          this.$message.success(this.$t('MODIFY_SUCCESS'))
          this.close(true)
        })
      },
      // 新增节点
      addNode() {
        nodeApi.add(this.nodeData).then((res) => {
          this.$message.success(this.$t('ADD_SUCCESS'))
          this.close(true)
        })
      },
      // 更新节点信息
      updateNode() {
        nodeApi.mod(this.nodeData).then((res) => {
          this.$message.success(this.$t('MODIFY_SUCCESS'))
          this.close(true)
        })
      },
      // 区域搜索条件改变
      regionChange(data) {
        this.nodeData.roomId = ''
        // 如果修改就不清空节点类型
        this.nodeData.nodeType =
          this.type === 'add' && !this.isprev ? '' : this.nodeData.nodeType
        // 还原上一步操作
        this.isprev = false
        this.roomList = this.baseRegionList.filter((i) => i.parentId === data)
        this.nodeData.stationId = data
        this.stationData = this.baseRegionList.find((i) => i.regionId === data) || {}
        // 判断当前选择的站点是否是虚拟站点
        this.curNodeType = !!this.stationData.virtualFlag
        // 如果站点不是虚拟站点清空节点类型下的数据
        if (!this.curNodeType) {
          this.nodeData.properties.spliceClosure = this.$options.data().nodeData.properties.spliceClosure
        }
      },
      close(load) {
        this.$emit('close', load)
        this.nodeData = this.$options.data().nodeData
      }
    }
  }
</script>

<style scoped></style>
